<template>
  <div id="LiveRoom" class="room">
    <div class="main flex-row js-between">
      <div ref="videoArea" :style="{height:leftHeight,overflow:'auto'}" class="center op-area">
        <div v-if="video" class="videoStatus">{{ downStatusFormat[video.downStatus].value }}</div>
        <!--class: s-border -->
        <div id="mainContainer" class="up">
          <live-video-area-view
            v-if="video && video.sourceUrl"
            id="mainPlayer"
            ref="mainPlayer"
            :url="video.taskUrl?video.taskUrl:video.sourceUrl"
            style="width: 100%; height: 100%;"
            @watchState="watchState"
          />
        </div>
        <div class="down  flex-row ai-center ">
          <div class="top_operation">
            <el-divider content-position="right">视频操作栏</el-divider>
            <div class="buttons">
              <p>
                <span v-show="!isPlay" class="" @click="onPlay">
                  <img src="../../../assets/icon/play.png" alt="">
                </span>
                <span v-show="isPlay" class="" @click="onPause">
                  <img src="../../../assets/icon/suspend.png" alt="">
                </span>
              </p>
              <p>
                <span style="margin-right:8px;" @click="onSaveStart">
                  <img v-show="vStart" src="../../../assets/icon/select_start.png" alt="">
                  <img v-show="!vStart" src="../../../assets/icon/start.png" alt="">
                </span>
                <span @click="onSaveEnd">
                  <img v-show="vEnd" src="../../../assets/icon/select_stop.png" alt="">
                  <img v-show="!vEnd" src="../../../assets/icon/stop.png" alt="">
                </span>
              </p>
              <p class="quick">
                <span class="back" @click="onMove(second,false)">
                  <img src="../../../assets/icon/back.png" alt="">
                </span>
                <el-dropdown @command="handleCommand">
                  <span class="el-dropdown-link">
                    {{ second }} s
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="(item, index) in timeList"
                      :command="item.t"
                      :key="index"
                    >
                      {{ item.t }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <span class="go" @click="onMove(second,true)">
                  <img src="../../../assets/icon/go.png" alt="">
                </span>
              </p>
            </div>
            <el-divider content-position="right">剪辑基本信息填写</el-divider>
            <div class="write">
              <span class="input">
                <el-input v-model="clipModule.title" type="textarea" resize="none" placeholder="填写视频名称"/>
              </span>
              <span class="select">
                <el-select v-model="clipModule.confId" class="setWidth" placeholder="选择视频模板">
                  <el-option
                    v-for="item in module_option"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </span>
            </div>
          </div>
          <div v-show="vtimes.length != 0" class="timeInfo">
            <div style="text-align:right;">
              <el-button-group>
                <el-button round type="warning" size="mini" @click="onSaveOneClip(true)">合条剪辑</el-button>
                <el-button round type="warning" size="mini" @click="vtimes = []">全部删除</el-button>
              </el-button-group>
              <el-divider content-position="left">打点记录</el-divider>
            </div>
            <div class="list">
              <draggable v-model="vtimes" :options="dragOptions" element="p" @update="onDrag">
                <p v-for="(item, index) in vtimes" :key="index" class="timeitem">
                  <span>
                    <span style="margin-right:20px;" class="">开始时间：{{ formatTime(item.s) }}</span>
                    <span class="">结束时间：{{ formatTime(item.e) }}</span>
                  </span>
                  <span class="operation">
                    <el-tooltip content="单条剪辑" placement="top">
                      <el-button size="mini" type="success" icon="el-icon-scissors" circle @click="onSaveOneClip(false,item)"/>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="delTimes(index)"/>
                    </el-tooltip>
                    <el-tooltip content="拖动排序" placement="top">
                      <el-button class="sort" size="mini" type="warning" icon="el-icon-sort" circle/>
                    </el-tooltip>
                  </span>
                </p>
              </draggable>
            </div>
          </div>
        </div>
      </div>
      <div v-loading.lock="LoadingData" :style="{height:computedHeight}" class="right flex-col js-start" style="position: relative;">
        <div class="tabsAndClipNum">
          <el-tabs v-model="tabs" type="card" style="margin:0 8px;">
            <el-tab-pane label="剪辑" name="1"/>
            <el-tab-pane label="AI翻译" name="2"/>
          </el-tabs>
          <div v-show="tabs==1" style="padding-bottom:10px;margin:0 8px;">
            <el-button class="filter-item" style="background:#F56C6C;color:#fff;" @click="saveAll">
              批量剪辑
            </el-button>
            <span style="font-weight:bold;">素材数 {{ clipForm.length }}</span>
          </div>
        </div>
        <!-- 剪辑列表 -->
        <div v-show="tabs==1" class="clipListInfo">
          <div v-if="clipForm.length === 0" class="noData">暂无剪辑记录</div>
          <div v-for="(item, index) in clipForm" :key="index" class="oneclipinfo">
            <el-form ref="form" :inline="false" label-position="right" label-width="90px">
              <div class="top">
                <span style="color:#F56C6C;margin-left:20px;">{{ item.id }}</span>
                <span style="color:#F56C6C;margin-left:20px;">{{ clipStatusFormat[item.status].value }}</span>
                <span class="del" @click="delclip(item,index)">
                  <img src="../../../assets/icon/close.png" alt="">
                </span>
              </div>
              <el-form :inline="true" label-position="right" label-width="90px">
                <el-form-item label="视频名称">
                  <el-input v-model="item.title" class="setWidth" type="textarea" style="" resize="none" />
                </el-form-item>
                <el-form-item label="关键字">
                  <el-input v-model="item.keywords" class="setWidth" type="textarea" style="" resize="none" placeholder="多个关键字用逗号隔开"/>
                </el-form-item>
              </el-form>
              <el-form :inline="true" label-position="right" label-width="90px">
                <el-form-item label="所属地区">
                  <el-cascader
                    v-model="item.loc"
                    :options="cityList"
                    :props="{
                      expandTrigger: 'hover',
                      value:'id',
                      label:'name'
                    }"
                    class="setWidth"
                  />
                </el-form-item>
                <el-form-item label="展示模板">
                  <el-select v-model="item.confId" class="select setWidth" placeholder="请选择">
                    <el-option
                      v-for="item in module_option"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-form :inline="true" label-position="right" label-width="90px">
                <el-form-item label="节目分类">
                  <el-select v-model="item.lenType" class="select setWidth" placeholder="请选择">
                    <el-option
                      v-for="item in lenTypeFormat"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="所属标签">
                  <div style="cursor:pointer;" @click="viewCate(item.cateList,index)">
                    <span>
                      {{ cateToText(item.cateList) }}
                      <el-link v-if="item.cateList.length>2" :underline="false" icon="el-icon-more">更多</el-link>
                    </span>
                    <span v-if="item.cateList.length==0">
                      <el-link :underline="false" icon="el-icon-circle-plus">点击添加</el-link>
                    </span>
                  </div>
                </el-form-item>
              </el-form>
              <el-form-item label="起始时间" class="timeInfo">
                <div class="info">
                  <div class="time">时长 {{ getTimeLength(item) }} s</div>
                  <!-- 单条剪辑的时间显示 -->
                  <div v-if="!item.multi">
                    <el-input v-model="item.startTime" style="width:100px;" resize="none" placeholder="开始时间" @blur="changeStr(item,item.multi)"/>
                    -
                    <el-input v-model="item.endTime" style="width:100px;" resize="none" placeholder="结束时间" @blur="changeend(item,item.multi)"/>
                  </div>
                  <!-- 合条剪辑的时间显示 -->
                  <div v-else>
                    <p v-for="(t, index) in item.parts" :key="index" class="time">
                      <el-input v-model="t.start" style="width:100px;" resize="none" placeholder="开始时间" @blur="changeStr(t,item.multi)"/>
                      -
                      <el-input v-model="t.end" style="width:100px;" resize="none" placeholder="结束时间" @blur="changeend(t,item.multi)"/>
                    </p>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="展示封面" class="upload">
                <img-upload
                  :file-list="item.picList"
                  @onSuccess="(fileList)=>{uploadCallback(fileList,item)}"
                  @onRemove="(fileList)=>{uploadCallback(fileList,item)}"
                />
              </el-form-item>
              <div class="buttons">
                <span class="deep_blue_btn" @click="updateInfo(item,index)">保存信息</span>
                <span :class="video.downStatus==0?'disabled':''" class="deep_blue_btn" @click="submitClip(item,index)">开始剪辑</span>
              </div>
              <div v-if="video.downStatus==0" class="tip">*当前视频未下载完成，无法进行剪辑</div>
            </el-form>
          </div>
        </div>
        <!-- AI翻译 -->
        <div v-show="tabs==2" class="AI">
          <div v-if="textTranslation.length > 0" class="text">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in textTranslation"
                :key="index"
                :timestamp="`${formatTime(item.b/1000)} - ${formatTime(item.e/1000)}`"
                :color="item.f==1?'#F56C6C':''"
                :class="item.f==1?'speechitem':''"
                type="info"
                placement="top"
              >
                <div class="tag">
                  <img v-show="item.recordStart" src="../../../assets/icon/s.png" alt="">
                  <img v-show="item.recordEnd" src="../../../assets/icon/e.png" alt="">
                </div>
                <div>
                  <el-popover
                    placement="left-end"
                    width="auto"
                    trigger="hover"
                  >
                    <el-button slot="reference" icon="el-icon-location" size="mini" circle>打点</el-button>
                    <div>
                      <el-button-group>
                        <el-button type="danger" size="mini" @click="AIrecord(item,index,'start')">记录起点</el-button>
                        <el-button type="danger" size="mini" @click="AIrecord(item,index,'end')">记录终点</el-button>
                      </el-button-group>
                    </div>
                  </el-popover>
                  <span style="cursor:pointer;" @click="jumpVideoPosition(item.b)">{{ item.text }}</span>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
          <!-- 空状态 -->
          <div v-else class="noData">抱歉，暂未生成翻译内容</div>
          <div v-show="(AITimeRecord.s || AITimeRecord.s == 0) && AITimeRecord.e" class="AIclip" @click="onSaveOneClip(false,AITimeRecord)">立即剪辑</div>
        </div>
      </div>
    </div>
    <!-- 视频分类标签选择窗口 -->
    <el-dialog
      :visible.sync="cateVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="选择标签"
      width="30%"
    >
      <div style="width:100%;text-align:center;">
        <el-cascader
          v-model="cateData.list"
          :options="cateOptions"
          :props="{
            expandTrigger: 'hover',
            value:'id',
            label:'name',
            multiple: true
          }"
          style="width:75%;"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cateVisible = false">取 消</el-button>
        <el-button type="primary" @click="appendToList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { apiVideo } from '../../../api/clip/task'
import LocalVideoAreaView from './views/LocalVideoAreaView'
import DivButton from '../../../components/common/DivButton'
import FileUploader from '../../../components/common/FileUploader'
import ObjectUtil from '../../../utils/object-util'
import Fn from '../../../utils/fn'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiUpload } from '../../../api/upload'
import { apiCommon } from '../../../api/common'
import TimeUtil from '../../../utils/time-util'
import { getToken } from '../../../utils/auth'
import LiveVideoAreaView from './views/LiveVideoAreaView'
import imgUpload from '../../../components/common/imgUpload'
import {
  ClipListSourceTypeContants,
  MeterialClipTypeContants,
  downStatusFormat,
  clipStatusFormat,
  lenTypeFormat
} from '../../../mixin/MixinContants'
import draggable from 'vuedraggable'
import elementResizeDetectorMaker from 'element-resize-detector'
import { Poptip } from 'view-design'
export default {
  name: 'RadioMeterialClipEdit',
  components: {
    LiveVideoAreaView,
    LocalVideoAreaView,
    DivButton,
    FileUploader,
    draggable,
    imgUpload,
    Poptip
  },
  mixins: [
    ClipListSourceTypeContants.mixin,
    MeterialClipTypeContants.mixin,
    downStatusFormat.mixin,
    clipStatusFormat.mixin,
    lenTypeFormat.mixin
  ],
  data() {
    return {
      lastStartPosition: 0,
      lastEndPosition: 0,
      AITimeRecord: {}, // AI打点的时间记录
      leftHeight: 0,
      cateData: {
        list: [],
        index: 0
      }, // 级联框分类数据
      cateVisible: false,
      second: 0.1,
      isPlay: false,
      uploadUrl: apiUpload.upload_url,
      header: { 'Authorization': 'Bearer ' + getToken() },
      // AI翻译文本
      textTranslation: [],
      tabs: '1',
      // 右侧列表的高
      computedHeight: 0,
      dragOptions: {
        handle: '.sort',
        animation: 500
      },
      vtimes: [],
      // 快进快退档位
      timeList: [
        { t: 0.1 },
        { t: 0.2 },
        { t: 0.5 },
        { t: 1 },
        { t: 2 }
      ],
      LoadingData: true,
      // 默认关键字
      defaultKeywords: '',
      cityList: [],
      // 素材任务id
      taskId: undefined,
      video: undefined,
      vStart: undefined, // 开始时间
      vEnd: undefined, // 结束时间
      // 生成剪辑的params
      clipModule: {
        title: '',
        confId: '',
        posterUrl: '',
        clipType: 1
      },
      // 右侧片段列表
      clipForm: [],
      // 模板选项
      module_option: [],
      cateOptions: [], // 分类列表
      taskTitle: '',
      // 监听对象
      elemListen: null
    }
  },
  created() {
    this.taskId = this.$route.query.id
    this.taskTitle = this.$route.query.title || ''
    this.Init()
  },
  mounted() {
    this.leftHeight = `${document.body.clientHeight - 80}px`// 80=tabbar高度+内外边距宽度
    this.elemListen = elementResizeDetectorMaker()
    this.elemListen.listenTo(document.querySelector('.op-area'), element => {
      this.$nextTick(() => {
        this.computedHeight = `${element.clientHeight}px`
      })
    })
  },
  destroyed() {
    this.elemListen.removeAllListeners(document.querySelector('.op-area'))
  },
  methods: {
    // 初始化页面
    async Init() {
      this.getclipTempl()
      this.videoDetail()
      await this.getAreaList()
      await this.relationCategory()
      this.getcliplist()
    },
    // 计算视频时长
    getTimeLength(item) {
      let length = 0
      if (item.multi) {
        length = item.parts.reduce((pre, next) => {
          pre += next['length']
          return pre
        }, 0)
      } else {
        length = item['length']
      }
      return Number(length).toFixed(2)
    },
    viewCate(list, index) {
      this.cateData = { list, index }
      this.cateVisible = true
    },
    // 分类级联数据转为 一级/二级，... 文本
    cateToText(cate) {
      const cateMap = [...new Set([].concat(...cate))]
      let text = []
      this.cateOptions.forEach(p => {
        if (cateMap.includes(p.id)) {
          p.children && p.children.forEach(c => {
            if (cateMap.includes(c.id)) {
              text.push(`${p.name}/${c.name}`)
            }
          })
        }
      })
      text = text.length > 2 ? text.splice(0, 2).join(',') : text.join(',')
      return text
    },
    // 将选择的分类添加到对应的clip中
    appendToList() {
      const { list, index } = this.cateData
      this.clipForm[index].cateList = list
      this.cateVisible = false
    },
    handleCommand(val) {
      this.second = val
    },
    // 获取视频播放状态
    watchState(player) {
      this.isPlay = player.playing
    },
    /**
     * @name: 快进快退时间格式化
     * @param {*} val 时间参数
     * @return {*}
     */
    fot(val) {
      if (val > 0) {
        return val
      } else {
        return String(val).split('-')[1]
      }
    },
    // 时间格式化工具方法
    formatTime(val) {
      return TimeUtil.secondsToTime(val)
    },
    // 图片上传回调
    uploadCallback(fileList, item) {
      const success = fileList.every(item => item.status === 'success')
      if (success) item.picList = fileList.map(item => ({ url: item.response ? item.response.datas.url : item.url }))
    },
    beforePosterUpload() {

    },
    // 跳转播放
    jumpVideoPosition(time) {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.currentTime(TimeUtil.millisecondtoSecond(time))
      }
    },
    delTimes(index) {
      this.vtimes.splice(index, 1)
    },
    // 拖拽排序触发
    onDrag(val) {
      console.log(val, '重排后的数组')
    },
    // tree结构格式化，去二级children
    formatList(list) {
      list.forEach(item => {
        item.children.forEach(c => {
          c.children = undefined
        })
      })
      return list
    },
    // 省市信息
    getAreaList() {
      return new Promise(async(resolve, reject) => {
        const [err, res] = await this.$await(apiCommon.arealist())
        if (res) {
          this.cityList = this.formatList(res.datas)
          resolve(res.datas)
        } else {
          reject(err)
        }
      })
    },
    // 获取关联的分类信息
    relationCategory() {
      return new Promise(async(resolve, reject) => {
        const [err, res] = await this.$await(apiMeterial.relationCategory())
        if (res) {
          this.cateOptions = this.formatList(res.datas)
          resolve(res.datas)
        } else {
          reject(err)
        }
      })
    },
    // 开始时间修改
    changeStr(item, multi) {
      const end = TimeUtil.TimeToseconds(multi ? item.end : item.endTime)
      const start = TimeUtil.TimeToseconds(multi ? item.start : item.startTime)
      if (start > end) {
        return this.toast.fail('结束时间不能小于开始时间')
      }
      item['length'] = (end - start)
    },
    // 结束时间修改
    changeend(item, multi) {
      const end = TimeUtil.TimeToseconds(multi ? item.end : item.endTime)
      const start = TimeUtil.TimeToseconds(multi ? item.start : item.startTime)
      if (start > end) {
        return this.toast.fail('结束时间不能小于开始时间')
      }
      item['length'] = (end - start)
    },
    /**
     * 格式化分类数据
     * @argument type 1[[...],[...]] to 一级:[],二级:[]  2一级:[],二级:[] to [[...],[...]]
    */
    formatCate(type, cateList) {
      let cateInfo = null
      let filterData = null
      if (type == 1) {
        filterData = [...new Set([].concat(...cateList))]
        cateInfo = { cateOneList: [], cateTwoList: [] }
        filterData.forEach(item => {
          this.cateOptions.forEach(cate => {
            if (item == cate.id) {
              cateInfo.cateOneList.push({ ...cate })
            } else {
              cate.children && cate.children.forEach(c => {
                if (item == c.id) {
                  cateInfo.cateTwoList.push({ ...c })
                }
              })
            }
          })
        })
      } else {
        cateInfo = []
        cateList && cateList.forEach(item => {
          item.children.forEach(c => {
            cateInfo.push([item.id, c.id])
          })
        })
      }
      return cateInfo
    },
    // 地区格式化
    formatLoc(loc) {
      let cityInfo = []
      this.cityList && this.cityList.forEach(p => {
        p.children && p.children.forEach(c => {
          if (c.id == loc) {
            cityInfo = [p.id, c.id]
          }
        })
      })
      return cityInfo
    },
    // 获取素材下的所有剪辑
    async getcliplist() {
      const form = {
        taskId: this.taskId,
        clipType: 1
      }
      const [err, res] = await this.$await(apiVideo.cliplist_all(form))
      if (res) {
        const result = res.datas.list || []
        this.LoadingData = false
        this.clipForm = result.map(item => {
          // 处理合条的时间
          let parts = item.multi ? JSON.parse(item.parts) : []
          parts = ObjectUtil.notEmpty(parts) ? parts.map(t => {
            return {
              ...t,
              start: TimeUtil.secondsToTime(t.start),
              end: TimeUtil.secondsToTime(t.end)
            }
          }) : undefined
          // 处理图片
          let picList = (item.picList && ObjectUtil.confirmArray(JSON.parse(item.picList))) || []
          picList = picList.map(item => ({ url: item }))
          return {
            ...item,
            parts,
            endTime: item.endTime ? TimeUtil.secondsToTime(item.endTime) : undefined,
            startTime: item.startTime ? TimeUtil.secondsToTime(item.startTime) : undefined,
            prov: item.prov || '',
            readOnly: true,
            loc: this.formatLoc(item.loc) || [],
            cateList: this.formatCate(2, item.cateTrees),
            picList
          }
        })
      }
    },
    // 删除某个片段
    delclip: Fn.Confirm(async function(item, index) {
      const [err, res] = await this.$await(apiVideo.delClip({ id: item.id }))
      if (res) {
        this.toast.success('删除成功')
        this.getcliplist()
      }
    }, '确定删除吗？'),
    // 获取剪辑模板
    async getclipTempl() {
      const [err, res] = await this.$await(apiVideo.templOptions())
      if (res) {
        this.module_option = res.datas.list
      }
    },
    // 获取期数id下的分类
    async getIdCate(playId) {
      const [err, res] = await this.$await(apiMeterial.searchPeriodId({ playId }))
      if (res) {
        const result = res.datas || {}
        const { radioName, channelName, programmeName, liveHostsName } = result
        this.defaultKeywords = [radioName, channelName, programmeName, liveHostsName].join(',') || ''
      }
    },
    fixed(num) {
      return parseFloat(num.toFixed(3))
    },
    // 素材剪辑信息
    async videoDetail() {
      const [err, res] = await this.$await(apiVideo.read({ id: this.taskId }))
      if (res) {
        this.video = res.datas
        this.taskTitle = this.video.title
        if (this.video.playId) {
          this.getIdCate(this.video.playId)
        }
        let { beSplit, textSegment } = res.datas
        let text = [] // 文本
        let speech = [] // 话术
        beSplit = this.isJSON(beSplit) && JSON.parse(beSplit)
        textSegment = this.isJSON(textSegment) && JSON.parse(textSegment)
        if (beSplit && JSON.parse(beSplit).length) {
          speech = JSON.parse(beSplit).map(item => {
            return item.c.map(_c => {
              return {
                ..._c,
                f: item.f
              }
            })
          }).flat()
        }
        text = textSegment.length ? textSegment : []
        this.textTranslation = speech.length ? speech : text
      }
    },
    // 判断是字符串是否是json格式
    isJSON(json) {
      try {
        if (typeof JSON.parse(json) === 'object') {
          return true
        }
      } catch (error) {
        return false
      }
      return false
    },
    // 设置封面
    onSetPoster() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.clipModule.posterUrl = this.$refs.mainPlayer.clipImage()
      }
    },
    // 记录起点
    onSaveStart() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.stop()
        this.vStart = this.$refs.mainPlayer.currentTime()
        console.log(this.vStart)
      }
      if (this.vStart >= this.vEnd) {
        this.$notify.warning({
          title: '提示',
          message: '起点不能大于终点，请重新选择'
        })
        this.vEnd = undefined
      }
    },
    // 记录终点
    onSaveEnd: Fn.Debounce(function() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.stop()
        this.vEnd = this.$refs.mainPlayer.currentTime()
      }
      if (this.vStart >= this.vEnd) {
        this.$notify.warning({
          title: '提示',
          message: '起点不能大于终点，请重新选择'
        })
        this.vEnd = undefined
      } else {
        if (ObjectUtil.allNotNull(this.vStart, this.vEnd)) {
          this.vtimes.push({
            s: this.fixed(this.vStart),
            e: this.fixed(this.vEnd),
            // s:this.vStart,
            // e:this.vEnd,
            length: this.fixed((this.vEnd - this.vStart))
          })
          this.vStart = this.vEnd = undefined
        }
      }
    }),
    /**
     * @name: AI打点
     * @param {*行数据} lineItem
     * @param {*下标} position
     * @param {*起点终点} direction
     * @return {*null}
     */
    AIrecord(lineItem, position, direction) {
      const { b, e } = lineItem
      // 起点
      if (direction === 'start') {
        this.$set(this.textTranslation[this.lastStartPosition], 'recordStart', false)
        this.lastStartPosition = position
        this.$nextTick(() => {
          this.$set(this.textTranslation[position], 'recordStart', true)
          this.AITimeRecord.s = this.fixed(b / 1000)
        })
      } else { // 终点
        this.$set(this.textTranslation[this.lastEndPosition], 'recordEnd', false)
        this.lastEndPosition = position
        this.$nextTick(() => {
          this.$set(this.textTranslation[position], 'recordEnd', true)
          this.AITimeRecord.e = this.fixed(e / 1000)
          this.AITimeRecord['length'] = this.$math.subtract(this.AITimeRecord.e, this.AITimeRecord.s)
        })
      }
      this.$nextTick(() => {
        const { s: AIstart, e: AIend } = this.AITimeRecord
        if (AIend && AIstart >= AIend) {
          this.$notify.warning({
            title: '提示',
            message: '起点不能大于终点，请重新选择'
          })
          this.AITimeRecord.e = 0
          this.$set(this.textTranslation[this.lastEndPosition], 'recordEnd', false)
        }
      })
      console.log(this.AITimeRecord, 'uu')
    },
    // 前进后退
    onMove(step, state) {
      if (!step) return this.toast.fail('请选择快进快退倍数')
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        if (state) {
          this.$refs.mainPlayer.currentTime(this.$refs.mainPlayer.currentTime() + step)
        } else {
          this.$refs.mainPlayer.currentTime(this.$refs.mainPlayer.currentTime() - step)
        }
      }
    },
    // 暂停
    onPause() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.vEnd = this.$refs.mainPlayer.stop()
      }
    },
    // 播放
    onPlay() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.vEnd = this.$refs.mainPlayer.play()
      }
    },
    // 剪辑信息非空校验
    validate() {
      const that = this
      // if (!ObjectUtil.notEmpty(that.clipModule.title)) {
      //   that.$notify.warning({
      //     title: '提示',
      //     message: '剪辑标题不能为空'
      //   })
      //   return false
      // }
      if (!that.clipModule.confId) {
        that.$notify.warning({
          title: '提示',
          message: '选择模板'
        })
        return false
      }
      // if (that.clipModule.endTime <= that.clipModule.startTime) {
      //   that.$notify.warning({
      //     title: '提示',
      //     message: '开始时间不能大于结束时间'
      //   })
      //   return false
      // }
      return true
    },
    // 校验下载状态
    downStatus() {
      const { downStatus } = this.video
      if (downStatus == 1) {
        return true
      } else if (downStatus == 2) {
        this.toast.fail('任务下载失败，无法剪辑')
        return false
      } else {
        this.toast.fail('任务下载中，稍后再试')
        return false
      }
    },
    /**
     * 设置单、合条剪辑对应的起止时间参数
     * @argument clipinfo 剪辑数据
     * @argument multi 是否为单条剪辑 true 合条 false 单条
    */
    clipTimefiled(clipInfo) {
      if (clipInfo.multi) {
        const parts = clipInfo.parts.map(_time => {
          return {
            ..._time,
            start: TimeUtil.TimeToseconds(_time.start),
            end: TimeUtil.TimeToseconds(_time.end)
          }
        })
        return { parts: JSON.stringify(parts) }
      } else {
        return {
          endTime: TimeUtil.TimeToseconds(clipInfo.endTime),
          startTime: TimeUtil.TimeToseconds(clipInfo.startTime)
        }
      }
    },
    // 批量剪辑
    saveAll: Fn.Confirm(function() {
      if (!this.downStatus()) return
      const notSaves = this.clipForm
        .filter(item => item.status == -1)
        .map(item => ({ ...item, ...this.clipTimefiled(item) }))
      const noParams = notSaves.filter(item => item.cateList.length == 0)
      if (noParams.length > 0) return this.toast.fail('请设置分类')
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const promise = []
      notSaves.forEach(ns => {
        const { cateOneList, cateTwoList } = this.formatCate(1, ns.cateList)
        ns.cateOneList = cateOneList
        ns.cateTwoList = cateTwoList
        ns.picList = (ObjectUtil.notEmpty(ns.picList) && JSON.stringify(ns.picList.map(item => item.url))) || ''
        this.$delete(ns, 'status')
        this.$delete(ns, 'cateList')
        this.$delete(ns, 'readOnly')
        promise.push(apiVideo.createAndClip(ns))
      })
      Promise.all(promise).then(res => {
        loading.close()
        this.toast.success('保存成功')
        this.getcliplist()
      }).catch(err => {
        console.log(err)
        loading.close()
      })
    }, '是否批量剪辑所有未开始剪辑的视频？'),
    /**
     * @param {*} oneClip 剪辑数据
     * @param {*} clip 接口
     * @return {*}
     */
    async clipInterface(oneClip, clip) {
      const item = { ...oneClip, ...this.clipTimefiled(oneClip) }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const { cateOneList, cateTwoList } = this.formatCate(1, item.cateList)
      item.cateOneList = cateOneList
      item.cateTwoList = cateTwoList
      item.prov = item.loc[0] || ''
      item.loc = item.loc[1] || ''
      item.picList = (ObjectUtil.notEmpty(item.picList) && JSON.stringify(item.picList.map(item => item.url))) || ''
      this.$delete(item, 'status')
      this.$delete(item, 'readOnly')
      this.$delete(item, 'cateList')
      const [err, res] = await this.$await(clip(item))
      if (res) {
        this.$notify.success({
          title: '成功',
          message: '提交剪辑任务成功'
        })
        this.getcliplist()
      }
      loading.close()
    },
    // 正式剪辑
    submitClip(clip) {
      if (!this.downStatus()) return
      if (clip.cateList.length == 0) {
        return this.toast.fail('请设置分类标签')
      }
      this.clipInterface(clip, apiVideo.createAndClip)
    },
    // 修改素材的基本信息（分类）
    updateInfo(item) {
      if (item.readOnly) {
        item.readOnly = !item.readOnly
        return
      } else {
        if (item.cateList.length === 0) {
          return this.toast.fail('请设置分类标签')
        }
        // if (item.loc.length === 0) {
        //   return this.toast.fail('请选择地区')
        // }
        item.readOnly = !item.readOnly
      }
      this.clipInterface(item, apiVideo.updateClip)
    },
    // 生成剪辑片段
    onSaveOneClip: Fn.Debounce(async function(multi, time = {}) {
      const that = this
      if (!that.validate()) return
      let timeObj = {}
      if (multi) {
        timeObj = {
          parts: JSON.stringify(this.vtimes.map(item => ({ start: item.s, end: item.e, length: item['length'] })))
        }
      } else {
        timeObj = {
          startTime: time.s,
          endTime: time.e,
          length: time['length']
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const form = {
        ...this.clipModule,
        ...timeObj,
        multi,
        cateOneList: [],
        cateTwoList: [],
        taskId: this.taskId,
        keywords: this.defaultKeywords || ''
      }
      const [err, res] = await this.$await(apiVideo.onlycreate(form))
      if (res) {
        this.toast.success('创建成功')
        this.getcliplist()
        this.vtimes = []
        this.vStart = this.vEnd = undefined
      }
      loading.close()
    })
  }
}
</script>
<style lang="scss" scoped>
  button{
    margin-left: 0px !important;
    margin-right: 10px;
  }
  .noData{
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
    color:#909399;
    font-weight: bold;
    font-size: 18px;
  }
  .setWidth{
    width:190px;
  }
  //noinspection ALL
  video::-internal-media-controls-download-button {
    display:none !important;
  }
  .view-box {
    /*margin: 5px;*/
    padding: 5px;
  }
  .room {
    padding: 10px;
    /*84 = navbar + tags-view = 50 +34 */
    // height: calc(100vh - 84px);
    height:auto;
    width: 100%;
    position: relative;
    overflow: auto;
    background-color: #f6f7fb;
    .top {
      height: 70px;
    }
    .main {
      width:100%;
      align-items: flex-start;
      .op-area {
        position: relative;
        width: 100%;
        // height: 100%;
        // min-height: calc(100vh);
        min-width: 640px;
        max-width: 58%;
        display: flex;
        flex-direction: column;
        // justify-content: space-between;
        padding:10px;
        .videoStatus{
          position: absolute;
          left: 10px;
          top:10px;
          padding:10px;
          background: rgba(0,0,0,.4);
          color:#fff;
          font-weight: bold;
          z-index: 10;
          border-radius: 15px 0 15px 0;
        }
        .up {
          position: relative;
          // height: calc(100% - 100px);
          // height:500px;
          // min-height: 480px;
        }
        .down {
          min-height: 100px;
          padding-top:8px;
          display: block;
          .top_operation{
            width:100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding:10px;
            margin-bottom: 10px;
            background-color: #fff;
            .buttons{
              display: inline-flex;
              align-items: center;
              p{
                margin-right: 50px;
                img{
                  width:30px;
                  height:30px;
                }
                &>span{
                  cursor: pointer;
                }
              }
              .quick{
                display: inline-flex;
                align-items: center;
                .el-dropdown-link{
                  margin: 0 10px;
                  transition: .5s;
                  padding:4px;
                }
                .el-dropdown-link:hover{
                  background: #f5f7f8;
                }
                .go,.back{
                  display: inline-flex;
                }
              }
            }
            ::v-deep .write{
              width:100%;
              position: relative;
              .el-textarea__inner,.el-input--medium .el-input__inner{
                height:50px;
              }
              .el-input__inner{
                border-radius: 4px 0 0 4px;
                background: #F2F6FC;
              }
              .select{
                position: absolute;
                left:0;
                top:0;
              }
              .input{
                textarea{
                  padding-left: 200px;
                  box-sizing: border-box;
                }
              }
            }
          }
          .inputs{
            width:100%;
            text-align: right;
            .i-select{
              margin:10px 0;
            }
          }
          .timeInfo{
            position: relative;
            width:100%;
            // max-height: 180px;
            // overflow: auto;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            min-height: 100px;
            margin-top: 20px;
            padding:10px;
            box-sizing: border-box;
            background-color: #fff;
            .list{
              max-height: 120px;
              overflow: auto;
            }
            .timeitem{
              padding:5px 0;
              border-bottom:1px solid rgba(192,196,204,.3);
              display: flex;
              align-items: center;
              justify-content: space-between;
              .operation{
                text-align: right;
              }
            }
          }
          button{
            margin:0;
          }
        }
      }
      .right {
        width: 50%;
        min-width: 200px;
        padding:10px 0 10px 10px;
        .valid {
          border: solid 0.5px red;
        }
        .AI{
          padding:5px;
          overflow-y:auto;
          .tag{
            position: absolute;
            left:200px;
            top:0;
            width:30px;
            height:30px;
            img{
              width:100%;
              height:100%;
            }
          }
          .AIclip{
            position:fixed;
            right:10px;
            top:200px;
            border-radius: 30px;
            text-align: center;
            background-color: #E6A23C;
            padding:15px 20px;
            box-sizing: border-box;
            box-shadow: 0 0 10px rgba(245, 108, 108,.5);
            color:#fff;
            font-weight: bold;
            cursor: pointer;
          }
        }
        ::v-deep .speechitem .el-timeline-item__content{
          color:#F56C6C;
          // filter: grayscale(100%);
        }
        .tabsAndClipNum{
          padding-right: 5px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .clipListInfo{
          overflow-y:auto;
          padding:5px;
          .oneclipinfo{
            position: relative;
            box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
            padding-bottom: 8px;
            margin:10px 5px 0;
            background-color: #fff;
            box-sizing: border-box;
            .top{
              display: inline-flex;
              align-items: center;
              width:100%;
              &:first-child{
                font-weight: bold;
              }
              .del{
                position: absolute;
                top:0;
                right:0;
                display: inline-block;
                width:30px;
                height:30px;
                margin-left: auto;
                cursor: pointer;
                img{
                  width:100%;
                  height:100%;
                }
              }
            }
            .buttons{
              width:100%;
              text-align: center;
              margin: 10px 0;
            }
            .tip{
              text-align: center;
              color:#F56C6C;
            }
            .moduleitem{
              display: flex;
              align-items: center;
              margin-bottom: 10px;
              .title{
                width:80px;
                text-align: right;
                display: inline-block;
                margin-right: 8px;
              }
              .imgbox{
                display: inline-block;
                width:150px;
                height:90px;
                background:#fff;
                margin-right: 10px;
                img{
                  width:100%;
                  height:100%;
                }
              }
              .info{
                p{
                  margin:6px 0;
                }
              }
              .cate{
                .cate_list{
                  display: flex;
                  flex-wrap: wrap;
                  align-items: center;
                  .list{
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    margin-right: 10px;
                    margin-bottom: 10px;
                    .select{
                      width:150px;
                      margin-right: 10px;
                      margin-bottom: 5px;
                    }
                  }
                }
              }
            }
            ::v-deep .upload{
              .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                width:50px;
                height:50px;
              }
              .avatar-uploader .el-upload:hover {
                border-color: #409EFF;
              }
              .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 100%;
                height: 100%;
                line-height: 50px;
                text-align: center;
                position: absolute;
                left:50%;
                top:50%;
                transform: translate(-50%,-50%);
              }
              .el-upload-list__item{
                width:50px;
                height:50px;
                img{
                  width:100%;
                  height:100%;
                }
              }
            }
            .timeInfo{
              .time{
                margin-bottom: 5px;
              }
            }
            .cateinfo{
              display: inherit;
              .cate{
                .cate_title{
                  margin-bottom: 10px;
                }
              }
            }
          }
        }
      }
    }
  }
  .s-border {
    // margin: 2px;
    // padding-right:8px;
    border: solid 1px rgba(1,1,1,0.1);
  }
  .button {
    text-align: center;
    width: auto;
    min-width: 80px;
    height: 50px;
    padding: 10px;
    margin: 0 5px;
  }
  .function {
    text-align: center;
    width: 80px;
    height: 80px;
    padding: 10px 0;
    margin: 5px;
  }
  .setting {
    text-align: center;
    width: 60px;
    height: 60px;
  }
</style>
